package com.hean.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;

import com.hean.entity.Cube;
import com.hean.view.MyView;

public class ShowCube extends Activity{
	private Cube cube;
	private MyView view;
	private static final int MSG_DOWN = 1;
	private InnerThread t;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == MSG_DOWN) {
				view.invalidate();
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cube);
		cube=new Cube();
		view=(MyView) findViewById(R.id.view);
		view.setCube(cube);
//		onKeyDown(KeyEvent.KEYCODE_DPAD_UP, null);
//		cube.setX(0);
//		
//		view.invalidate();
		view.postInvalidate();
		System.out.println(view.getHeight()+",view3");
//		
//		System.out.println(getWindowManager().getDefaultDisplay().getHeight()+",activity");
//		
//		
//		System.out.println(view.getHeight()+",view4");
		t = new InnerThread();
		t.start();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		System.out.println(view.getHeight()+",view1");
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if(cube.getX()-5>=0)
			cube.setX(cube.getX()-5);
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if(cube.getX()+55<=this.getWindowManager().getDefaultDisplay().getWidth())
			cube.setX(cube.getX()+5);
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			this.t.setSleepTime();
			break;
		}
		
		view.invalidate();
		return super.onKeyDown(keyCode, event);
	}
	
	private class InnerThread extends Thread {
		private long sleepTime=500;
		public void setSleepTime(){
			sleepTime=10;
		}
		@Override
		public void run() {
			
			while (true) {
				System.out.println(view.getHeight()+",view2");
				if(cube.getY()+cube.getSize()+50>=ShowCube.this.getWindowManager().getDefaultDisplay().getHeight()){
					cube.setY(0);
					sleepTime=500;
//					break;
				}
				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException e) {}
				cube.setY(cube.getY() + 5);
				Message msg = new Message();
				msg.what = MSG_DOWN;
				handler.sendMessage(msg);
			}
		}
	}
}
